package com.sskj.jd.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sskj.core.exception.MException;
import com.sskj.dingtalk.exception.OApiException;
import com.sskj.dingtalk.utils.CalendarUtil;
import com.sskj.dingtalk.utils.CodingUtil;
import com.sskj.dingtalk.utils.HttpHelper;
import com.sskj.jd.domain.AnQuanXCJLQueryParam;
import com.sskj.jd.domain.entity.FoundWT;
import com.sskj.jd.domain.entity.JianDuJiLuCJJG;
import com.sskj.jd.domain.entity.JianDuJiLuRenYuan;
import com.sskj.jd.domain.entity.WenTiFILE;
import com.sskj.jd.domain.entity.WenTiIMG;
import com.sskj.jd.domain.entity.WenTiLX;
import com.sskj.jd.domain.entity.AnQuanXCJL;
import com.sskj.jd.repository.AnQuanXCJLRepository;
import com.sskj.jd.repository.EmployeeForRepository;
import com.sskj.jd.trans.AnQuanJDXCTrans;
import com.sskj.jd.vo.AnQuanJDXCVO;
import com.sskj.personnel.domain.entity.EmployeeEntity;
import com.sskj.personnel.repository.EmployeeRepository;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping(value = "/jd/aqxcjl", method = { RequestMethod.POST, RequestMethod.GET })
@Transactional
@Api(value = "安全监督巡查记录", description = "安全监督巡查记录")
public class AnQuanXCJLServiceImpl {

	protected final Log logger = LogFactory.getLog(AnQuanXCJLServiceImpl.class);

	@Autowired
	AnQuanXCJLRepository aqRepository;

	@Autowired
	EmployeeRepository employeeRepository;
	
	@Autowired
	EmployeeForRepository employeeForRepository;		

	@Value("${sskj.conf.restUrl}")
	private String restUrl;

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/page")
	@ApiImplicitParams({ @ApiImplicitParam(name = "coding", value = "记录编号", paramType = "form", dataType = "string"),
			@ApiImplicitParam(name = "engName", value = "工程名称", paramType = "form", dataType = "string"),
			@ApiImplicitParam(name = "pageNumber", value = "页号", paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "pageSize", value = "页的大小", paramType = "form", dataType = "int") })
	public Page<AnQuanXCJL> queryPage(@ApiIgnore AnQuanXCJLQueryParam AnQuanXCJLQueryParam,
			@ApiIgnore Pageable pageable) {

		Page<AnQuanXCJL> page = aqRepository.findPage(AnQuanXCJLQueryParam, pageable);
		return page;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/save", method = { RequestMethod.POST })
	@ApiOperation(value = "新增安全监督巡查记录", notes = "新增安全监督巡查记录", httpMethod = "POST")
	public void save(@RequestBody AnQuanXCJL aqXCJL) throws Exception {

		AnQuanXCJL oldAnQuanXCJL = null;

		if (aqXCJL.getId() != null) {
			oldAnQuanXCJL = aqRepository.get(aqXCJL.getId());
		}

		if (oldAnQuanXCJL == null) {
			String cdlike = "AQXC-" + CalendarUtil.getYearyyyy(Calendar.getInstance()) + "-%";
			Integer cdlen = 14;
			String maxCode = aqRepository.maxCode(cdlike, cdlen);
			String coding = CodingUtil.getMaxIDQuery(maxCode, cdlike, cdlen);
			aqXCJL.setCoding(coding);
			aqXCJL.getEng().setOid(aqXCJL.getEng().getId());

			aqXCJL.getEng().setId(null);

		}

		for (JianDuJiLuRenYuan jdry : aqXCJL.getJdrys()) {
			EmployeeEntity emp = employeeRepository.findByDD_Id(jdry.getEmplId());
			if (emp != null) {
				jdry.setUserId(emp.getResteasy_emp_id());
			}
			else
			{
				EmployeeEntity emp2 = employeeForRepository.findByName(jdry.getName());
				if (emp2 != null) {
					jdry.setEmplId(emp2.getDdId());
					jdry.setName(emp2.getName());					
					jdry.setUserId(emp2.getResteasy_emp_id());
				}				 
			}
			jdry.setJdjl(aqXCJL);
			jdry.setCreatorId(aqXCJL.getCreatorId());			


		}

		for (JianDuJiLuCJJG cjjg : aqXCJL.getCjjgs()) {
			cjjg.setJdjl(aqXCJL);
			cjjg.setCreatorId(aqXCJL.getCreatorId());

		}

		for (WenTiIMG img : aqXCJL.getImages()) {
			img.setJdjl(aqXCJL);
			img.setCreatorId(aqXCJL.getCreatorId());
		}

		for (FoundWT wt : aqXCJL.getWt()) {
			wt.setJdjl(aqXCJL);
			for (WenTiFILE file : wt.getFiles()) {
				file.setWt(wt);
				file.setCreatorId(aqXCJL.getCreatorId());
			}

			for (WenTiIMG img : wt.getImages()) {
				img.setWt(wt);
				img.setCreatorId(aqXCJL.getCreatorId());
			}

			for (WenTiLX lx : wt.getWtlx()) {
				lx.setWt(wt);
				lx.setCreatorId(aqXCJL.getCreatorId());
			}
		}

		aqRepository.save(aqXCJL);

	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/upload", method = { RequestMethod.POST })
	@ApiOperation(value = "上传安全监督巡查记录", notes = "上传安全监督巡查记录", httpMethod = "POST")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "安全监督巡查记录 IDS", paramType = "form", required = true, dataType = "string") })
	public void upload(String id) throws Exception {

		try {
			AnQuanXCJL oldAnQuanXCJL = aqRepository.get(id);
			oldAnQuanXCJL.setIsUpload(true);
			uploadJd(oldAnQuanXCJL);
			aqRepository.save(oldAnQuanXCJL);
		} catch (OApiException e) {
			e.printStackTrace();

			if (e.getErrCode() == 2) {
				throw new MException("request_timeout");
			} else {
				throw new MException("system_error");
			}

		}

	}

	// 同步往监督系统
	public void uploadJd(AnQuanXCJL aqXCJL) throws OApiException {

		AnQuanJDXCTrans trans = new AnQuanJDXCTrans(aqXCJL);
		AnQuanJDXCVO vo = trans.returnVO();
		EmployeeEntity emp = employeeRepository.findByDD_Id(aqXCJL.getCreatorId());
		if (emp != null) {
			vo.setCreateId(emp.getResteasy_emp_id());
		}
		JSONObject obj = HttpHelper.httpPost(restUrl + "dingtalk/jd/aqjdxc/up", vo);
		if (null == obj) {
			throw new OApiException(1, "");
		}

	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/get", method = { RequestMethod.POST })
	@ApiImplicitParams({ @ApiImplicitParam(name = "spId", value = "记录ID", paramType = "form", dataType = "string") })
	@ApiOperation(value = "获取安全监督巡查记录", notes = "获取安全监督巡查记录", httpMethod = "GET")
	public AnQuanXCJL get(String spId) throws Exception {

		AnQuanXCJL aqXCJL = aqRepository.findOneById(spId);
		return aqXCJL;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/del", method = { RequestMethod.POST, RequestMethod.DELETE })
	@ApiOperation(value = "删除安全监督巡查记录", notes = "删除安全监督巡查记录  多个安全监督巡查记录ID用,号分隔", httpMethod = "DELETE")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "安全监督巡查记录 IDS", paramType = "form", required = true, dataType = "string") })
	public void del(String id) {
		if (StringUtils.isNotEmpty(id)) {
			String[] idsArr = id.split(",");
			List<String> list = new ArrayList<String>();

			if (idsArr != null) {
				for (String idd : idsArr) {
					if (!idd.equals("ADMIN")) {
						list.add(idd);
					}
				}
				aqRepository.delete(list);
			}
		}
	}

}
